package ds_industry_2025.ds.ds_03.T3

import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

import java.util.Properties

/*
    3、请根据dws层表province_consumption_day_aggr计算出每个省份2020年4月的平均订单金额和该省所在地区平均订单金额相比较结果（
    “高/低/相同”）,存入MySQL数据库shtd_result的provinceavgcmpregion表中（表结构如下），然后在Linux的MySQL命令行中根据省份
    表主键、省平均订单金额、地区平均订单金额均为降序排序，查询出前5条，将SQL语句复制粘贴至客户端桌面【Release\任务B提交结果.docx】
    中对应的任务序号下，将执行结果截图粘贴至客户端桌面【Release\任务B提交结果.docx】中对应的任务序号下;
 */
object t3 {
  def main(args: Array[String]): Unit = {
    val spark = SparkSession.builder()
      .master("local[*]")
      .appName("t3")
      .config("hive.exec.dynamic.partition.mode","nonstrict")
      .config("spark.serializer","org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.extensions","org.apache.spark.sql.hudi.HoodieSparkSessionExtension")
      .enableHiveSupport()
      .getOrCreate()


    spark.table("dws.province_consumption_day_aggr")
      .where(col("year")===2020 && col("month")===4)
      .createOrReplaceTempView("data")

    val result = spark.sql(
      """
        |select
        |province_id,province_name,province_avg,
        |region_id,region_name,region_avg,
        |case
        |when province_avg > region_avg then "高"
        |when province_avg < region_avg then "低"
        |else "相同"
        |end as comparison
        |from(
        |select
        |province_id,province_name,province_avg,
        |round( region_amount / region_count) as region_avg,
        |region_id,region_name
        |from(
        |select distinct
        |province_id,province_name,province_avg,
        |sum(total_amount) over(partition by region_id,region_name) as region_amount,
        |sum(total_count) over(partition by region_id,region_name) as region_count,
        |region_id,region_name
        |from(
        |select
        |province_id,province_name,
        |round((total_amount / total_count)) as province_avg,
        |region_id,region_name,
        |total_amount,total_count
        |from data as d
        |) as r1
        |) as r2
        |) as r3
        |""".stripMargin)

    result.show()

    val conn=new Properties()
    conn.setProperty("user","root")
    conn.setProperty("password","123456")
    conn.setProperty("driver","com.mysql.jdbc.Driver")

    result.write.mode("overwrite")
      .jdbc("jdbc:mysql://192.168.40.110:3306/shtd_result?useSSL=false","provinceavgcmpregion",conn)

    // todo select * from provinceavgcmpregion order by province_id desc,province_avg desc,region_avg desc limit 5;


    spark.close()


  }

}
